<template>
  <div class="class-affair">
    <div class="class-affair-left">
      <el-calendar ref="calendar" v-model="dayDate">
        <template #header="{ date }">
          <div class="el-calendar__title">{{ date }}</div>
          <div class="el-calendar__button-group">
            <el-button-group>
              <el-button size="small" @click="selectDate('prev-month')" :icon="ArrowLeft" />
              <el-button size="small" type="primary" @click="selectDate('today')"> 今日 </el-button>
              <el-button size="small" @click="selectDate('next-month')" :icon="ArrowRight" />
            </el-button-group>
          </div>
        </template>
        <template #date-cell="{ data }">
          <div class="calendar-cell">
            <span>{{ data.day.split('-')[2] }}</span>
            <div class="flex mt-4px gap-col-4px">
              <template v-for="(dot, index) in getShowDot(data.day)" :key="index">
                <span class="calendar-dot" :class="[dot]"></span>
              </template>
            </div>
            <div v-if="isWeekHasEvent(data.day)" class="calendar-dot weekly weekly-done"></div>
          </div>
        </template>
      </el-calendar>
      <div
        class="text-#606266 text-14px p-12px flex gap-col-10px justify-center pointer-events-none"
      >
        <div><span class="calendar-dot handover"></span> 表示每日交班 </div>
        <div><span class="calendar-dot selfcheck"></span> 表示班级自查 </div>
        <div><span class="calendar-dot weekly"></span> 表示一周大事 </div>
      </div>
    </div>
    <div class="class-affair-right flex-1 bg-#fff p-20px overflow-x-hidden">
      <el-tabs v-model="currentTab">
        <el-tab-pane name="daily-handover" label="每日交班">
          <DailyHandover
            v-if="currentTab === 'daily-handover'"
            :date="selectedDate"
            :isToday="isToday"
            @refresh="getMonthData(oldMonth)"
          />
        </el-tab-pane>
        <el-tab-pane name="class-self-check" label="班级自查">
          <ClassSelfCheck
            v-if="currentTab === 'class-self-check'"
            :date="selectedDate"
            :isToday="isToday"
            @refresh="getMonthData(oldMonth)"
          />
        </el-tab-pane>
        <el-tab-pane name="weekly-event" label="一周大事">
          <WeeklyEvent
            v-if="currentTab === 'weekly-event'"
            :date="selectedDate"
            :isWeek="isWeek"
            @refresh="getMonthData(oldMonth)"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script setup lang="ts">
import type { CalendarDateType, CalendarInstance } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/formatTime'
import { ClassAssetApi } from '@/api/school/classAffairs'
import DailyHandover from './DailyHandover.vue' // 引入每日交班组件
import WeeklyEvent from './WeeklyEvent.vue' // 引入一周大事组件
import ClassSelfCheck from './ClassSelfCheck.vue' // 引入班级自查组件
import dayjs from 'dayjs'
import isoWeek from 'dayjs/plugin/isoWeek'
dayjs.extend(isoWeek)
const route = useRoute()
const calendar = ref<CalendarInstance>()
console.log(formatDate(new Date(), 'YYYY-MM-DD'), '---1')

const selectedDate = ref(formatDate(new Date(), 'YYYY-MM-DD'))
const dayDate = ref(new Date())
const monthData = ref<Recordable>({}) // 月份数据
const oldMonth = ref('')
const currentTab = ref('daily-handover') // 默认显示每日交班
const isToday = computed(() => {
  return dayjs().isSame(selectedDate.value, 'day')
})
const isWeek = computed(() => {
  return dayjs().isSame(selectedDate.value, 'isoWeek')
})
const selectDate = (val: CalendarDateType) => {
  if (!calendar.value) return
  calendar.value.selectDate(val)
}

const getMonthData = async (Month: string) => {
  oldMonth.value = Month
  try {
    const data = await ClassAssetApi.getScheduleByMonth({
      classId: route.query.id as string,
      month: Month
    })
    monthData.value = {}
    data?.forEach((item: any) => {
      const key = item.day.replace(/-/g, '')
      monthData.value[key] = {
        isHandoverDone: item.isHandoverDone,
        isSelfCheckDone: item.isSelfCheckDone,
        isWeeklyEventDone: item.isWeeklyEventDone
      }
    })
  } catch (error) {}
}
onMounted(() => {
  getMonthData(formatDate(dayDate.value, 'YYYYMM'))
})
watch(dayDate, (val) => {
  const month = formatDate(val, 'YYYYMM')
  const day = formatDate(val, 'YYYY-MM-DD')
  if (oldMonth.value !== month) {
    getMonthData(month)
  }
  if (day) {
    handleDayClick({ day })
  }
})

const getShowDot = (day: string) => {
  const key = day.replace(/-/g, '')
  const status = monthData.value?.[key]
  const dotArray: any = []
  if (!status) return dotArray
  if (status.isHandoverDone) {
    dotArray.push('handover')
  }
  // if (status.isWeeklyEventDone) {
  //   dotArray.push('weekly')
  // }
  if (status.isSelfCheckDone) {
    dotArray.push('selfcheck')
  }
  return dotArray
}

function handleDayClick(data: any) {
  selectedDate.value = data.day
}
// 判断指定日期所在的周是否有一周大事完成
const isWeekHasEvent = (date: string) => {
  // console.log(date, '---date11')
  if (!dayjs || !date) return false
  const weekStart = dayjs(date).isoWeekday(1) // 本周周一

  if (weekStart.isSame(date, 'day')) {
    const key = weekStart.format('YYYYMMDD')
    const status = monthData.value?.[key]
    if (status && status.isWeeklyEventDone) {
      return true
    }
  }
  return false
}
</script>

<style lang="scss" scoped>
.class-affair {
  display: flex;
  column-gap: 20px;
  flex: 1;
  min-height: $content-height;

  .class-affair-left {
    width: 400px;
    padding: 15px;
    padding-left: 20px;
    background-color: #fff;
    flex-shrink: 0;
  }
}

.calendar-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  vertical-align: middle;
  border-radius: 50%;
}

.calendar-dot.handover {
  background-color: green; // 绿色勾
}

.calendar-dot.weekly {
  background-color: blue; // 蓝色方块
}

.calendar-dot.selfcheck {
  background-color: orange; // 橙色圈
}

.calendar-cell {
  position: relative;
  display: flex;
  cursor: pointer;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.weekly-done {
  position: absolute;
  top: 15px;
  left: -20px;
}

:deep() {
  // .el-calendar {
  //   width: 312px;
  //   height: 100%;
  // }

  .el-calendar__header {
    padding: 2px;
  }

  .el-calendar__body {
    padding: 0;
  }

  .el-calendar-day {
    height: 50px !important;
    text-align: center;
  }

  .el-calendar-table td.is-selected {
    background-color: var(--el-color-primary-light-9) !important;
  }
}

.empty-tab {
  padding: 20px;
  color: #999;
  text-align: center;
}
</style>
